//
//  FengShuiCompassViewController.m
//  FengShuiCompass - Google AdMob Ads SDK Example
//
//  Copyright 2011 Google Inc. All rights reserved.
//

#import <QuartzCore/QuartzCore.h>
#import "FengShuiCompassViewController.h"

#define SHADOWX 7.0
#define SHADOWY 7.0

static NSString *gEighthText[] = {
    @"正北", @"東北", @"正東", @"東南", @"正南", @"西南", @"正西", @"西北"
};
static NSString *gSixteenthText[] = {
    @"N", @"NE", @"E", @"SE", @"S", @"SW", @"W", @"NW"
};
static NSString *gTwentyFourthText[] = {
    @"子",@"癸",@"丑",@"艮",@"寅",@"甲",@"卯",@"乙",@"辰",@"巽",@"巳",@"丙",@"午",
    @"丁",@"未",@"坤",@"申",@"庚",@"酉",@"辛",@"戌",@"乾",@"亥",@"壬"
};

@implementation FengShuiCompassViewController

- (void)makeAdRequest {
  // Measure the boundary of the wood grain.  The ad will center in it.
  CGFloat boundingWidth = self.view.bounds.size.width;
  CGFloat boundingY = backgroundView.bounds.size.height + SHADOWY;
  CGFloat boundingHeight = self.view.bounds.size.height - boundingY;

  // Calculate the position of a leaderboard banner ad.
  CGSize bannerSize = GAD_SIZE_728x90;
  CGRect frame = CGRectZero;
  frame.origin.x = (boundingWidth - bannerSize.width) / 2;
  frame.origin.y = (boundingHeight - bannerSize.height) / 2 + boundingY;
  frame.size = bannerSize;

  // Create a leaderboard ad.
  bannerView = [[GADBannerView alloc] initWithFrame:frame];
  [self.view addSubview:bannerView];

  // The root view controller is this object.
  bannerView.rootViewController = self;

  // The ad unit ID was assigned on www.admob.com when I downloaded the SDK.
  bannerView.adUnitID = @"a14da2849c38273";

  // Add a nice drop shadow on the ad.
  bannerView.layer.shadowColor = [UIColor blackColor].CGColor;
  bannerView.layer.shadowOpacity = 1.0;
  bannerView.layer.shadowRadius = 5.0;
  bannerView.layer.shadowOffset = CGSizeMake(SHADOWX, SHADOWY);

  // Fade the ad in.
  bannerView.alpha = 0.0;
  bannerView.delegate = self;

  // Make a test ad request on white listed devices.  In this case only the
  // simulator will get test ads.
  GADRequest *request = [GADRequest request];
  request.testDevices = [NSArray arrayWithObjects:
      GAD_SIMULATOR_ID,
      nil];
  [bannerView loadRequest:request];
}

- (void)loadView {
  [super loadView];

  // Create a shadow for the crosshairs above the compass.
  [compassShadowView.layer
      setAffineTransform:CGAffineTransformMakeTranslation(SHADOWX, SHADOWY)];

  // Get access to the device's compass.
  locationManager = [[CLLocationManager alloc] init];
  if (locationManager.headingAvailable == NO) {
#ifdef TARGET_IPHONE_SIMULATOR
    // The simulator never has a compass.  Do not issue an alert.  But do mock
    // a compass orientation to see it work.
    CLHeading *heading = [[[CLHeading alloc] init] autorelease];
    [self locationManager:locationManager didUpdateHeading:heading];
#else
    // No compass on this device.
    UIAlertView *alert =
        [[UIAlertView alloc] initWithTitle:@"No Compass"
                                   message:@"This device has no compass"
                                  delegate:nil
                         cancelButtonTitle:@"OK"
                         otherButtonTitles:nil];
    [alert show];
    [alert release];
#endif  // TARGET_IPHONE_SIMULATOR
  } else {
    // Heading service configuration.
    locationManager.headingFilter = 0.5;

    // Setup delegate callbacks.
    locationManager.delegate = self;

    // Start the compass.
    [locationManager startUpdatingHeading];
  }

  // Make an ad request.
  [self makeAdRequest];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)o {
  return o == UIInterfaceOrientationPortrait;
}

- (void)dealloc {
  // Always nil the delegate before release the ad.  Otherwise if an ad request
  // were on the network, when it came back it would call the delegate on this
  // free object and crash the application.
  bannerView.delegate = nil;
  [bannerView release];

  [locationManager release];
  [super dealloc];
}

#pragma mark CLLocationManagerDelegate methods

// This delegate method is invoked when the location manager has heading data.
- (void)locationManager:(CLLocationManager *)manager
       didUpdateHeading:(CLHeading *)heading {
#ifdef TARGET_IPHONE_SIMULATOR
  CLLocationDirection direction = 283.0;
#else
  CLLocationDirection direction = heading.magneticHeading;
#endif  // TARGET_IPHONE_SIMULATOR

  // Rotate animation.
  [UIView beginAnimations:@"RotateCompass" context:nil];
  [UIView setAnimationBeginsFromCurrentState:YES];
  [UIView setAnimationDuration:0.5];
  [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
  CGFloat radians = -direction/180.0*M_PI;
  CGAffineTransform rotation = CGAffineTransformMakeRotation(radians);
  [compassView.layer setAffineTransform:rotation];
  CGAffineTransform shadowXform =
      CGAffineTransformTranslate(rotation, SHADOWX, SHADOWY);
  [compassShadowView.layer setAffineTransform:shadowXform];
  [UIView commitAnimations];

  // Update label.
  NSString *eighth = gEighthText[(int)(((int)(direction+22.5)%360)/45)];
  NSString *sixteenth =
      gSixteenthText[(int)(((int)(direction+11.25)%360)/22.5)];
  NSString *twentyfourth =
      gTwentyFourthText[(int)(((int)(direction+7.5)%360)/15)];
  degreeLabel.text = [NSString stringWithFormat:@"%d˚", (int)(direction)];
  bearingLabel.text =
      [NSString stringWithFormat:@"%@ %@ %@", eighth, twentyfourth, sixteenth];
}

// This delegate method is invoked when the location manager encounters
// an error condition.
- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error {
  if ([error code] == kCLErrorDenied) {
    // This error indicates that the user has denied the application's request
    // to use location services.
    [manager stopUpdatingHeading];
  } else if ([error code] == kCLErrorHeadingFailure) {
    // This error indicates that the heading could not be determined, most
    // likely because of strong magnetic interference.
  }
}

#pragma mark GADBannerViewDelegate methods

- (void)adViewDidReceiveAd:(GADBannerView *)view {
  // Fade the ad in over 0.4 seconds.  This is a standard animation length for
  // iOS and is just enough to make the ad less jarring.
  [UIView beginAnimations:@"Fade In Ad" context:nil];
  [UIView setAnimationDuration:0.4];
  view.alpha = 1.0;
  [UIView commitAnimations];
}

@end
